package com.njcb.ams.support.security.service;

import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.pojo.dto.standard.EntityResponse;
import com.njcb.ams.util.AmsJsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author srxhx207
 */
@Component
public class LogoutAuthenticationHandler implements LogoutHandler {

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		response.setContentType("application/json;charset=utf-8");
		//清理用户会话
		String sessionId = request.getSession().getId();
        SessionRegistry sessionRegistry = AppContext.getBean(SessionRegistry.class);
		if(null != sessionRegistry && null != sessionId){
			sessionRegistry.removeSessionInformation(sessionId);
		}
		try {
			PrintWriter out = response.getWriter();
			out.write(AmsJsonUtils.objectToJson(EntityResponse.buildSucc()));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
